package com.bookshop.dao;

import com.bookshop.bean.PageBean;
import com.bookshop.bean.ResultBean;
import com.bookshop.bean.TypeBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component
public class TypeDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    public int insertType(TypeBean typeBean){
        String sql="INSERT INTO book_type (type_name,type_depict) VALUES (?,?)";
        return jdbcTemplate.update(sql,typeBean.getTypeName(),typeBean.getTypeDepict());
    }

    /**
     * 查询所有type类型表
     * @return
     */
    public List<TypeBean> selectAllTypes(){
        String sql = "SELECT type_id,type_name,type_depict FROM book_type";
        List<TypeBean> types = new ArrayList<>();
        types = jdbcTemplate.query(sql, new RowMapper<TypeBean>() {
            public TypeBean mapRow(ResultSet rs, int rowNum)throws SQLException{
                TypeBean type = new TypeBean();
                type.setTypeId(rs.getInt("type_id"));
                type.setTypeName(rs.getString("type_name"));
                type.setTypeDepict(rs.getString("type_depict"));
                return type;
            }
        });
        return types;
    }

    public List<TypeBean> selectAllTypesPages(PageBean page){
        String sql = "SELECT type_id,type_name,type_depict FROM book_type LIMIT ?,?";
        List<TypeBean> types = new ArrayList<>();
        types = jdbcTemplate.query(sql, new RowMapper<TypeBean>() {
            public TypeBean mapRow(ResultSet rs, int rowNum)throws SQLException{
                TypeBean type = new TypeBean();
                type.setTypeId(rs.getInt("type_id"));
                type.setTypeName(rs.getString("type_name"));
                type.setTypeDepict(rs.getString("type_depict"));
                return type;
            }
        },(page.getPageNow()-1)*page.getPageSize(),page.getPageSize());
        return types;
    }

    public int getRowCount(){
         String sql = "SELECT COUNT(type_id) FROM book_type";
         return jdbcTemplate.queryForObject(sql,Integer.class);
    }

    public int deleteType(Integer id){
        String sql = "DELETE FROM  book_type WHERE type_id = ?";
        return jdbcTemplate.update(sql,id);
    }

    public int updateType(TypeBean type){
        String sql = "UPDATE book_type SET type_name = ?,type_depict = ? WHERE type_id = ?";
        return jdbcTemplate.update(sql,type.getTypeName(),type.getTypeDepict(),type.getTypeId());
    }









}
